<?php

/**
 * Simple memcache class
 */
class memcacheExpand
{
    // memcache服务器IP
    private $serverIp;

    // memcache服务器端口
    private $serverPort;

    // memcache连接实例
    private $memcache;

    // 缓存超时KEY
    private $outTimeKey = '_outtime';

    // 缓存锁KEY
    private $lockKey = '_lock';

    public function __construct($serverIp, $serverPort)
    {
        $this->serverIp = $serverIp;
        $this->serverPort = $serverPort;
    }

    /**
     * 带锁的获取数据
     * @param string $key  缓存KEY
     * @return string|int|array
     */
    public function getByLock($key)
    {
        $result = NULL;

        $this->memcacheConnect();

        $lockKey = $key . $this->lockKey;
        $outTimeKey = $key . $this->outTimeKey;

        if($this->memcache->get($outTimeKey) || $this->memcache->get($lockKey))
        {
            $result = $this->memcache->get($key);
        }
        else
        {
            $this->memcache->add($lockKey, 1, 0, 60);

            $result = -1;
        }

        return $result;
    }

    /**
     * 带锁的更新数据
     * @param string $key  缓存KEY
     * @param string|array $val  缓存值
     * @param int $outTime  超时时间
     */
    public function setByLock($key, $val, $outTime = NULL)
    {
        $this->memcacheConnect();

        $lockKey = $key . $this->lockKey;
        $outTimeKey = $key . $this->outTimeKey;
		
        $this->memcache->add($outTimeKey, 1, 0, $outTime);

        $this->memcache->set($key, $val, 0, $outTime * 25);

        $this->unLock($key);
    }

    /**
     * 解除键值锁定
     */
    public function unLock($key)
    {
        $this->memcacheConnect();

        $lockKey = $key . $this->lockKey;
        $this->memcache->delete($lockKey);
    }

    /**
     * 创建memcache连接
     */
    private function memcacheConnect()
    {
        if((empty($this->memcache) || !is_object($this->memcache)))
        {
            $this->memcache = new Memcache;
            $this->memcache->connect($this->serverIp, $this->serverPort);
        }
    }

    /**
     * 未定义的方法都使用memcache原生的
     * @return int|bool|array
     */
    public function __call($functionName, $params)
    {
        (empty($this->memcache) || !is_object($this->memcache)) && $this->memcacheConnect();

        return call_user_func_array(array(& $this->memcache, $functionName), $params);
    }

    public function __destruct()
    {
        // 关闭memcache连接
        (!empty($this->memcache) || is_object($this->memcache)) && $this->memcache->close();
    }
}

?>